<template>
  <div class="app-container">
    <h1>歌手信息</h1>
    <div v-if="loading">加载中...</div>
    <div v-else>
      <p><strong>歌手ID：</strong>{{ person.id }}</p>
      <p><strong>歌手名称：</strong>{{ decodeURIComponent(person.name.replace(/\+/g, ' ')) }}</p>
    </div>
    <el-table v-loading="loading" :data="currentPageData" style="width: 100%">
      <!-- 添加行号列 -->
      <el-table-column width="150" align="center">
        <template #default="scope">
          <span style="margin-left: 16px">{{ scope.$index + 1 + (currentPage - 1) * pageSize }}</span>
        </template>
      </el-table-column>
      <el-table-column label="歌曲名称" prop="trackTitle" />
      <el-table-column label="歌手" prop="artistName" />
      <el-table-column label="播放次数" prop="trackPlayCount" />
    </el-table>
    <el-pagination
        v-model:currentPage="currentPage"
        v-model:pageSize="pageSize"
        :total="singerList.length"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup name="SingerDetail">
import { ref, computed, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { getTrackTitles } from "@/api/tracks/tracks.js";
import axios from "axios";
import {getPersons} from "@/api/persons/persons.js"; // 确保后端接口返回的数据结构正确

const route = useRoute();
const loading = ref(true);
const person = ref([]);
const singerList = ref([]); // 完整的歌曲列表数据
const currentPage = ref(1); // 当前页码
const pageSize = ref(10); // 每页显示的条数

// 计算当前页的数据
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return singerList.value.slice(start, end);
});

onMounted(() => {
  const personId = route.params.id;
  getSingerList(personId);
  fetchPersonInfo(personId);
});

/** 获取歌单信息 */
async function fetchPersonInfo(personId) {
  getPersons(personId).then(response => {
        person.value = response.data;
        console.info(person)
      }
  )
}

/** 获取歌单中歌曲列表 */
function getSingerList(personId) {
  loading.value = true;
  getTrackTitles(personId).then(response => {
    console.log("API 返回的数据：", response.data);
    // 处理返回的数据，替换 + 和 /_/
    singerList.value = response.data.map(item => ({
      trackTitle: decodeURIComponent(item.trackTitle.replace(/\+/g, ' ').replace("/_/","——")),
      artistName: decodeURIComponent(item.artistName.replace(/\+/g, ' ').replace("/_/","——")),
      trackPlayCount: item.trackPlayCount
    }));
    console.info(singerList.value);
    loading.value = false;
  }).catch(error => {
    console.error("获取歌手歌曲详情失败：", error);
    loading.value = false;
  });
}

/** 处理每页显示条数变化 */
function handleSizeChange(newSize) {
  pageSize.value = newSize;
}

/** 处理页码变化 */
function handleCurrentChange(newPage) {
  currentPage.value = newPage;
}
</script>

<style scoped>
.app-container {
  margin: 20px;
}
</style>
